#include "MallocAlign.h"
///////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////
void *malloc_align( int size, int align_size ) {
   char *ptr;
   char *ptr2;
   char *aligned_ptr;
   
   int align_mask = align_size - 1;

//printf("malloc: %d bytes requested, allocating %d bytes\n",size,size+align_size+4);
   ptr = (char *) malloc( size + align_size + sizeof(int) );
if( ptr == NULL ) printf( "request for %ld bytes returned NULL\n", size+align_size+sizeof(int) );
   if( ptr == NULL ) return( NULL );

   // reserve space for a int
   // then align
   ptr2 = ptr + sizeof(int);
   aligned_ptr = ptr2 + (align_size - ((size_t)ptr2 & align_mask));

   // int right before returned pointer contains data
   ptr2 = aligned_ptr - sizeof(int);
   *((int *)ptr2)=(int)(aligned_ptr - ptr);

//printf("malloc returned %x, returning %x\n",ptr,aligned_ptr);
   return(aligned_ptr);
}
///////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////
void free_align(char *ptr) {
   int *ptr2=(int *)ptr - 1;
   ptr -= *ptr2;
   free(ptr);
}

///////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////
void * realloc_align(char *ptr, unsigned int size, unsigned int align_size) {
int * ptr1;
int * ptr2 = (int *)ptr;
   //	int align_mask = align_size - 1;

ptr1 = (int *)malloc_align(size, align_size);

unsigned int i;
for( i = 0; i < size/4; i++ ) {
ptr1[i] = ptr2[i];
}

free_align(ptr);

return (void *)ptr1;
}
